package cos.utils;

import java.net.URL;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

public class GoogleTranslationGetter {

	private static final String BASE_URL = "http://lingvopro.abbyyonline.com/ru/Search/";

	public static String translate(String in) {
		if (isOK(in)) {
			final String sourceUrlString = BASE_URL
					+ Preferences.getInst().getTranslationDirection() + "/"
					+ in;
			try {
				Source source = new Source(new URL(sourceUrlString));
				source.fullSequentialParse();

				List<Element> linkElements = source
						.getAllElementsByClass("translation");

				if (linkElements.size() > 1) {
					String out = "";
					int temp = linkElements.size();
					for (int i = 1; i < (temp > 8 ? 8 : temp); i++) {
						String s = linkElements.get(i).getRenderer().toString();
						if (isOK(s))
							out = out + s + "; ";
					}
					out = out.replaceAll("\n", "");
					return in + " - " + out;
				} else
					return in + " - no translation for you!";

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	private static boolean isOK(String s) {
		return s != null && !s.equals(" ") && !s.isEmpty()
				&& !s.equals('\n' + "") && !s.equals(",") && !s.equals(";")
				&& !s.equals("\"") && !s.equals("");
	}
}
